import 'package:flutter/material.dart';
import 'package:shenling_wuliu/utils/http.dart';
import 'package:shenling_wuliu/utils/toast.dart';
import 'package:shenling_wuliu/utils/token.dart';

class Login extends StatefulWidget {
  const Login({super.key});

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  final Color customColor = const Color(0xFFEF4F3F);
  //账号与密码输入框控制器
  final TextEditingController _accountController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  //密码输入框是否显示密码
  bool _isPasswordVisible = true;
  // 正则表达式：仅允许字母和数字，长度为6~8位
  final RegExp _regex = RegExp(r'^[a-zA-Z0-9]{6,8}$');
  @override
  void initState() {
    super.initState();
    TokenManager().init();
    //为账号与密码设置默认值，以便于测试
    _accountController.text = 'lyt6667';
    _passwordController.text = '123456';
  }
  // 校验方法
  bool validateForm() {
    if (_accountController.text.isEmpty) {
      ToastUtil.showError('请输入账号');
      return false;
    }

    if (!_regex.hasMatch(_accountController.text)) {
      ToastUtil.showError('账号必须为6-8位字母或数字');
      return false;
    }

    if (_passwordController.text.isEmpty) {
      ToastUtil.showError('请输入密码');
      return false;
    }

    if (!_regex.hasMatch(_passwordController.text)) {
      ToastUtil.showError('密码必须为6-8位字母或数字');
      return false;
    }

    return true;
  }
  //登录逻辑
  getLogin() async{
    //校验成功才能登录
    if(validateForm()) {
      try{
        var res = await http.post('/driver/login/account', data: {
        'account': _accountController.text,
        'password': _passwordController.text
      });
      TokenManager().saveToken(res['data']);
      
      ToastUtil.showSuccess('登录成功');
      //  跳转到首页
      Navigator.pushNamed(context, '/tabbar');
      }catch(e){
        ToastUtil.showError('登录失败');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text('神领物流'),
        centerTitle: true,
        automaticallyImplyLeading: false,
        elevation: 0,
        titleTextStyle: TextStyle(
          fontSize: 15
        ),
      ),
      body: Container(
        padding: EdgeInsets.symmetric(horizontal: 20,vertical: 30),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            //第一行，账号登录文本
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  '账号登录',
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                SizedBox(width: 10),
                Row(
                  children: [
                      Text(
                        '手机登录',
                        style: TextStyle(
                          fontSize: 14,
                          color: customColor,
                        )
                      ),
                  Icon(
                        Icons.arrow_forward_ios_rounded,
                        size: 14,
                        color: customColor,
                      ),
                  ],
                )
              ],
            ),
            SizedBox(height: 20),
            //第二行，账号输入
            TextField(
              controller: _accountController,
              keyboardType: TextInputType.phone,
              decoration: InputDecoration(
                 labelText: '账号',
                  hintText: '请输入账号',
              ),
            ),
            SizedBox(height: 10),
            //第三行，密码输入
            TextField(
              controller: _passwordController,
              obscureText: _isPasswordVisible,
              decoration: InputDecoration(
                labelText: '密码',
                hintText: '请输入密码',
                suffixIcon: IconButton(
                  icon: Icon(_isPasswordVisible ? Icons.visibility_off : Icons.visibility),
                  iconSize: 15,
                  onPressed: () {
                    setState(() {
                      _isPasswordVisible = !_isPasswordVisible;
                    });
                  },
                ),
              ),
            ),
            SizedBox(height: 20),
            //第四行，登录按钮
            Container(
              width: MediaQuery.of(context).size.width,
              // backgroundColor: '#EF4F3F',
              child: ElevatedButton(
              onPressed: () {
                getLogin();
              },
              style: ElevatedButton.styleFrom(
                  backgroundColor: customColor, // 应用自定义颜色
                  foregroundColor: Colors.white,
                  padding: EdgeInsets.symmetric(vertical: 16),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8),
                  ),
              ),
              child: Text('登录',style: TextStyle(color: Colors.white,fontSize: 16)),
            ),
            )
          ],
        ),
      ),
    );
  }
}